<template>
	<my-page title="浏览历史" :is-back="true" :is-tabbar="false">
		<!-- 资产列表 -->
		<view v-if="historyList.length > 0">
			<view v-for="(group, groupIndex) in groupedHistory" :key="groupIndex">
				<!-- 日期分割线 -->
				<view class="date-divider">
					<text class="date-text">{{group.date}}</text>
				</view>
				
				<!-- 当日资产列表 -->
				<view class="asset-list">
					<view 
					class="asset-item" 
					v-for="(item, index) in group.items" 
					:key="index"
					@click="goToDetail(item)"
				>
					<view class="asset-img-container">
						<image class="asset-img" :src="getImageUrl(item.imageUrl)" mode="aspectFill"></image>
						<view v-if="getAssetStatusName(item.assetStatus)" class="status-badge" :class="getStatusClass(item.assetStatus)">{{getAssetStatusName(item.assetStatus)}}</view>
					</view>
					<view class="asset-info">
						<view class="asset-name">{{item.name}}</view>
						<view class="asset-area">{{item.area}}</view>
						<view class="asset-price-box">
							<view class="asset-price">
								<text v-if="shouldShowRentPrice(item)">出租价格:{{item.rent}}</text>
								<text v-if="shouldShowTransferPrice(item)" class="transfer-price">出售价格:{{item.transferPrice}}</text>
							</view>
							<view class="asset-tag" :class="getTagClass(item.type)">{{getTypeName(item.type)}}</view>
						</view>
					</view>
				</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view v-else class="empty-state">
			<!-- <image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image> -->
			<text class="empty-text">暂无浏览历史</text>
		</view>
		
		<!-- 清空历史按钮 -->
		<view class="clear-btn" v-if="historyList.length > 0" @click="clearHistory">
			<text class="clear-text">清空历史记录</text>
		</view>
	</my-page>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import MyPage from '@/components/MyPage.vue'
import { getDictData } from '@/api/system'
import { onLoad, onShow } from '@dcloudio/uni-app'

// 资产类型字典
const typeDict = ref([])
const assetStatusData = ref([])

// 历史记录列表
const historyList = ref([])

// 按日期分组的历史记录
const groupedHistory = computed(() => {
	// 按日期分组
	const groups = {}
	
	historyList.value.forEach(item => {
		if (!groups[item.date]) {
			groups[item.date] = []
		}
		groups[item.date].push(item)
	})
	
	// 转换为数组格式
	const result = []
	for (const date in groups) {
		result.push({
			date: date,
			items: groups[date]
		})
	}
	
	// 按日期排序（最新日期在前）
	result.sort((a, b) => {
		const dateA = new Date(a.date)
		const dateB = new Date(b.date)
		return dateB - dateA
	})
	
	return result
})

// 初始化字典数据
const initDictData = async () => {
	try {
		// 获取资产类型字典
		const assetTypeRes = await getDictData('asset_type')
		if (assetTypeRes.code === 200 && assetTypeRes.data) {
			typeDict.value = assetTypeRes.data.map(item => ({
				label: item.dictLabel,
				value: item.dictValue
			}))
		}
		
		// 获取资产状态字典
		const assetStatusRes = await getDictData('asset_status')
		if (assetStatusRes.code === 200 && assetStatusRes.data) {
			assetStatusData.value = assetStatusRes.data.map(item => ({
				label: item.dictLabel,
				value: item.dictValue
			}))
		}
	} catch (error) {
		console.error('加载字典数据失败', error)
	}
}

// 获取浏览历史
const getHistory = () => {
	try {
		const history = uni.getStorageSync('assetViewHistory')
		if (history) {
			historyList.value = JSON.parse(history)
		} else {
			historyList.value = []
		}
	} catch (e) {
		console.error('获取浏览历史失败', e)
		historyList.value = []
	}
}

// 清空历史记录
const clearHistory = () => {
	uni.showModal({
		title: '提示',
		content: '确定要清空所有浏览历史吗？',
		success: (res) => {
			if (res.confirm) {
				try {
					uni.removeStorageSync('assetViewHistory')
					historyList.value = []
					uni.showToast({
						title: '历史记录已清空',
						icon: 'success'
					})
				} catch (e) {
					console.error('清空历史记录失败', e)
					uni.showToast({
						title: '操作失败，请重试',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 获取资产类型名称
const getTypeName = (type) => {
	// 如果字典数据已加载
	if (typeDict.value && typeDict.value.length > 0) {
		const typeItem = typeDict.value.find(item => item.value == type)
		if (typeItem) return typeItem.label
	}
	
	// 默认类型映射
	const typeMap = {
		0: '商铺',
		1: '住宅',
		2: '办公室',
		3: '厂房',
		4: '仓库'
	}
	
	return typeMap[type] || '其他'
}

// 根据类型获取标签样式类
const getTagClass = (type) => {
	const tagClasses = {
		0: 'tag-shop',
		1: 'tag-house',
		2: 'tag-office',
		3: 'tag-factory',
		4: 'tag-warehouse'
	}
	return tagClasses[type] || 'tag-other'
}

// 根据状态值获取状态名称
const getAssetStatusName = (status) => {
	// 从字典数据中查找状态名称
	if (assetStatusData.value && assetStatusData.value.length > 0) {
		const statusItem = assetStatusData.value.find(item => item.value == status)
		if (statusItem) return statusItem.label
	}
	
	// 默认状态映射
	const statusMap = {
		0: '闲置中',
		1: '展示中',
		2: '已租赁'
	}
	
	return statusMap[status]
}

// 根据状态值获取状态样式类
const getStatusClass = (status) => {
	const statusClasses = {
		0: 'status-idle',     // 闲置中
		1: 'status-display',  // 展示中
		2: 'status-rented'    // 已租赁
	}
	return statusClasses[status] || 'status-unknown'
}

// 根据盘活方式判断是否显示出租价格
const shouldShowRentPrice = (item) => {
	const method = item.revitalizationMethod
	const hasRentPrice = item.rent
	
	if (!hasRentPrice) return false
	
	return method === '出租' || method === '租售均可'|| method === '先租后让'
}

// 根据盘活方式判断是否显示出售价格
const shouldShowTransferPrice = (item) => {
	const method = item.revitalizationMethod
	const hasTransferPrice = item.transferPrice
	
	if (!hasTransferPrice) return false
	
	return method === '出售' || method === '租售均可'|| method === '先租后让'
}

// 处理图片URL
const getImageUrl = (imageUrl) => {
	if (!imageUrl) return '/static/images/suoluetu.png'
	
	// 确保imageUrl是字符串类型
	if (typeof imageUrl !== 'string') {
		return '/static/images/suoluetu.png'
	}
	
	// 分割图片URL，取第一个
	const firstImage = imageUrl.split(',')[0]
	
	// 检查是否已包含http
	if (firstImage.startsWith('http')) {
		return firstImage
	}
	
	// 拼接基础URL
	return import.meta.env.VITE_APP_BASE_API + firstImage
}

// 跳转详情页
const goToDetail = (item) => {
	uni.navigateTo({
		url: `/pages/asset/detail?id=${item.id}`
	})
}

// 在页面加载时获取数据
onMounted(() => {
	initDictData()
	getHistory()
})

// 页面显示时刷新历史记录
onShow && onShow(() => {
	getHistory()
})
</script>

<style lang="scss" scoped>
@import '@/static/styles/index.scss';

// 日期分割线
.date-divider {
	padding: 20rpx 30rpx 10rpx;
	background-color: #f5f5f5;
	
	.date-text {
		font-size: 28rpx;
		color: #666;
		font-weight: bold;
	}
}

// 资产列表样式
.asset-list {
	padding: 0 30rpx;
	
	.asset-item {
		display: flex;
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		
		.asset-img-container {
			position: relative;
			width: 220rpx;
			height: 160rpx;
			margin: 20rpx;
			// 右上角状态标签
			.status-badge {
				position: absolute;
				top: 0;
				right: 0;
				padding: 4rpx 8rpx;
				border-radius: 8rpx;
				font-size: 26rpx;
				color: #fff;
				z-index: 10;
				
				&.status-idle {
					background-color: #f39c12; // 橙色 - 闲置中
				}
				
				&.status-display {
					background-color: #3498db; // 蓝色 - 展示中
				}
				
				&.status-rented {
					background-color: #27ae60; // 绿色 - 已租赁
				}
				
				&.status-unknown {
					background-color: #95a5a6; // 灰色 - 未知状态
				}
			}
		}
		
		.asset-img {
			width: 100%;
			height: 100%;
			border-radius: 8rpx;
		}
		
		.asset-info {
			flex: 1;
			padding: 20rpx 20rpx 20rpx 0;
			
			.asset-name {
				font-size: 32rpx;
				color: #333;
				margin-bottom: 10rpx;
				font-weight: bold;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
			
			.asset-area {
				font-size: 28rpx;
				color: #999;
				margin-bottom: 20rpx;
			}
			
			.asset-price-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.asset-price {
					font-size: 28rpx;
					color: #ff5a5f;
					font-weight: bold;
					display: flex;
					flex-direction: column;
					
					.transfer-price {
						color: #ff9500;
						font-size: 24rpx;
						margin-top: 5rpx;
					}
				}
				
				.asset-tag {
					display: inline-block;
					padding: 4rpx 12rpx;
					font-size: 20rpx;
					border-radius: 4rpx;
					
					&.tag-shop {
						background-color: rgba(52, 195, 143, 0.1);
						color: #34c38f;
					}
					
					&.tag-house {
						background-color: rgba(241, 180, 76, 0.1);
						color: #f1b44c;
					}
					
					&.tag-office {
						background-color: rgba(80, 165, 241, 0.1);
						color: #50a5f1;
					}
					
					&.tag-factory {
						background-color: rgba(223, 71, 89, 0.1);
						color: #df4759;
					}
					
					&.tag-warehouse {
						background-color: rgba(102, 88, 221, 0.1);
						color: #6658dd;
					}
					
					&.tag-other {
					background-color: rgba(100, 100, 100, 0.1);
					color: #646464;
				}
			}
		}
		
	}
}
}

// 空状态样式
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
	
	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}
	
	.empty-text {
		font-size: 30rpx;
		color: #999;
	}
}

// 清空按钮样式
.clear-btn {
	margin: 30rpx;
	padding: 20rpx 0;
	background-color: #f5f5f5;
	border-radius: 10rpx;
	text-align: center;
	
	.clear-text {
		font-size: 30rpx;
		color: #666;
	}
}
</style>